package rong;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JPanel;

public class TreePanel extends JPanel {
	
	static final int MAX_W = 80;
	static final int MIN_W = 20;
	RBTree t;
	int l;
	int px;
	int py;

	public TreePanel(RBTree t) {
		this.t = t;
	}

	Map<PointKey, Node> positionMap;

	public Node getByXY(int x, int y) {
		return positionMap.get(new PointKey(x, y));
	}

	@Override
	public void paint(Graphics g) {
		positionMap = new HashMap();
		if (t==null || t.root == null) {
			px = py = l;
			return;
		}
		int ch = t.getHeight();
		px = getWidth() / 2;
		py = getHeight() / (ch + 2);
		int w = px / 2;
		int h = py;
		int minw = (int)(getWidth() / Math.pow(2, ch));
		if (minw>MAX_W) {
			minw = MAX_W;
		}
		if (minw <MIN_W) {
			minw = MIN_W;
		}
		l = minw;
		super.paint(g);
		Graphics2D g2d = (Graphics2D) g;
		drawNode(g2d, t.root, px, py, w, h);
	}

	private void drawNode(Graphics2D g2d, Node node, int x, int y, int w, int h) {
		positionMap.put(new PointKey(x, y), node);
		int r = l / 2;
		if (node.left != null) {
			g2d.setColor(Color.BLUE);
			g2d.drawLine(x + r, y + r, x - w / 2 + r, y + h + r);
			drawNode(g2d, node.left, x - w / 2, y + h, w / 2, h);
		}
		if (node.right != null) {
			g2d.setColor(Color.BLUE);
			g2d.drawLine(x + r, y + r, x + w / 2 + r, y + h + r);
			drawNode(g2d, node.right, x + w / 2, y + h, w / 2, h);
		}
		g2d.setColor(((RBNode)node).red ? Color.RED : Color.BLACK);
		g2d.fillArc(x, y, l, l, 0, 360);
		g2d.setFont(new Font("Tahoma", Font.BOLD, r));
		g2d.setColor(Color.WHITE);
		g2d.drawString(node.data + "", x + r/2, y + r/2*3);
	}

	class PointKey {
		int x;
		int y;

		public PointKey(int x, int y) {
			this.x = x;
			this.y = y;
		}

		public int hashCode() {
			return 0;
		}

		public boolean equals(Object obj) {
			if (obj == null || !(obj instanceof PointKey)) {
				return false;
			}
			PointKey k = (PointKey) obj;
			return (x - k.x) * (x - k.x) + (y - k.y) * (y - k.y) <= l * l;
		}
		public String toString() {
			return "PointKey:(" + x + ","+y+")";
		}
	}
}
